<template>
  <div class="code-layout">

    <!-- <div class="code-materials">
      <div>
        <plug-state :statusStr="status" />
        <br />
      </div>
      <div class="file">
        <file-list :biz_id="versionNow.id" type="workspace" />
      </div>
      <md-preview :biz_id="versionNow.id" type="workspace" class="preview" />
    </div> -->

    <div class="code-info">
      <div class="code-info-item">
        <h3 class="info-title">基本信息 <i class="el-icon-edit-outline edit" @click="updateTask"/></h3>
        <ul class="info-item">
          <li>
            <span class="key">名称:</span>
            <span class="val">{{ detailData.name }}</span>
          </li>
          <li>
            <span class="key"> 创建人： </span>
            <span class="val">{{
                detailData.create_user && (versionNow.create_user.nick_name ||
                  versionNow.create_user.username)
              }}</span>
          </li>
          <li>
            <span class="key">创建时间： </span>
            <span class="val">{{ versionNow.create_time }}</span>
          </li>
        </ul>
      </div>

      <div class="code-info-item">
        <h3 class="info-title">仿真信息 <i class="el-icon-edit-outline edit" @click="updateSimulationEnv"/></h3>
        <ul class="info-item">
          <li>
            <span class="key">仿真名称:</span>
            <span class="val">{{
                versionNow.simulation_node_group.image.name
              }}</span>
          </li>
          <!--          <li>-->
          <!--            <span class="key">想定名称:</span>-->
          <!--            <span class="val">{{ versionNow.scenario.name }}</span>-->
          <!--          </li>-->
        </ul>
      </div>

      <div class="code-info-item">
        <h3 class="info-title">开发环境<i class="el-icon-edit-outline edit" @click="updateEnv"/></h3>
        <dl class="code-dl" v-for="(e) in versionNow.node_group_list" :key="e.id">
          <ul class="info-item">
            <li>
              <span class="key">节点类型:</span>
              <span class="val">{{ nodeTypeMaps[e.type] }}</span>
            </li>
            <li>
              <span class="key">资源组:</span>
              <span class="val">{{ e.product.name }}</span>
            </li>
            <li>
              <span class="key">镜像:</span>
              <span class="val">{{ e.image.name }}</span>
            </li>
            <li>
              <span class="key">命令行:</span>
              <span class="val">{{ e.command }}</span>
            </li>
            <li>
              <span class="key">数量:</span>
              <span class="val">{{ e.pod_num }}</span>
            </li>
          </ul>
        </dl>
      </div>

      <div class="code-info-item">
        <h3 class="info-title">超参<i class="el-icon-edit-outline edit" @click="updateParam"/></h3>
        <dl class="code-dl" v-for="(e, i) in versionNow.parameter_list" :key="i">
          <ul class="info-item">
            <li>
              <span class="key">显示名 {{ e.name }}</span>
              <span class="val">参数名 {{ e.key }}</span>
              <span class="val">参数值 {{ e.value }}</span>
            </li>
          </ul>
        </dl>
      </div>
    </div>

    <!-- <el-form class="form myself-form" ref="taskForm" :model="taskForm" :rules="taskSubmitRules" label-width="120px">
        <el-dialog :visible.sync="showTaskDialog" title="模型训练" width="840px">
          <el-form-item label="名称" prop="name">
            <el-input type="text" v-model="taskForm.name" />
          </el-form-item>
          <el-form-item label="描述" prop="desc">
            <el-input type="textarea" :rows="3" v-model="taskForm.desc" />
          </el-form-item>
          <span slot="footer" class="dialog-footer">
            <el-button type="primary" @click="commitTask">确定</el-button>
            <el-button class="none-type" @click="cancelTask">取消</el-button>
          </span>
        </el-dialog>
      </el-form> -->

    <DialogBox title="模型训练" :visible="showTaskDialog" :confirm="commitTask" :close="cancelTask">
      <el-form class="form myself-form" ref="taskForm" :model="taskForm" :rules="taskSubmitRules" label-width="120px">
        <el-form-item label="名称" prop="name">
          <el-input type="text" v-model="taskForm.name"/>
        </el-form-item>
        <el-form-item label="描述" prop="desc">
          <el-input type="textarea" :rows="3" v-model="taskForm.desc"/>
        </el-form-item>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="commitTask">确定</el-button>
          <el-button class="none-type" @click="cancelTask">取消</el-button>
        </span>
      </el-form>
    </DialogBox>

    <DialogBox title="开发环境基本信息" :visible="showEnvDialog" :confirm="commitEnv" :close="cancelEnv">
      <el-form class="form myself-form" ref="envForm" :rules="submitEnvRules" :model="versionNow" label-width="120px">
        <div class="node-module">
          <h3 class="node-module-title">主节点</h3>
          <el-form-item label="环境" prop="mainNodeImageId">
            <el-cascader v-model="mainNode.image_group" :options="imageOptions" :show-all-levels="false"
                         class="full-extent-select"></el-cascader>
          </el-form-item>
          <el-form-item label="资源组" prop="mainProduct">
            <el-select v-model="mainNode.product_id" prop="main_product" class="full-extent-select">
              <el-option v-for="item in productOptions" :value="item.id" :label="item.name" :key="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="启动命令行">
            <el-input type="textarea" :rows="2" v-model="mainNode.command"/>
          </el-form-item>
          <div class="right-btn-box" v-if="slaveNodeList.length == 0">
            <span class="outin-handle">
              <a href="javascript:;" @click="addSlaveNode()">增加</a>
            </span>
          </div>
        </div>
        <div v-for="(tag, i) in slaveNodeList" :key="tag.id">
          <div class="node-module">
            <h3 class="node-module-title">从节点</h3>
            <el-form-item label="环境" prop="slaveImage">
              <el-cascader v-model="tag.image_group" :options="imageOptions" :show-all-levels="false"
                           class="full-extent-select"></el-cascader>
            </el-form-item>
            <!--            <el-form-item label="资源组">-->
            <!--              <el-select v-model="tag.product_id" class="full-extent-select">-->
            <!--                <el-option v-for="item in productOptions" :value="item.id" :label="item.name" :key="item.id">-->
            <!--                </el-option>-->
            <!--              </el-select>-->
            <!--            </el-form-item>-->
            <el-form-item label="启动命令行">
              <el-input type="textarea" :rows="2" v-model="tag.command"/>
            </el-form-item>
            <el-form-item label="数量">
              <el-input-number v-model="tag.pod_num"></el-input-number>
            </el-form-item>
            <div class="right-btn-box">
              <span class="outin-handle">
                <a href="javascript:;" @click="delSlaveNode(i)">删除</a>
                <a href="javascript:;" @click="addSlaveNode()" v-if="i == slaveNodeList.length - 1">增加</a>
              </span>
            </div>
          </div>
        </div>
      </el-form>
    </DialogBox>

    <DialogBox title="仿真信息" :visible="showSimulationDialog" :confirm="commitSimulation" :close="cancelSimulation">
      <el-form class="form myself-form" ref="simulationForm" :model="versionNow" label-width="120px"
               :rules="simulationSubmitRules">

        <el-form-item label="仿真环境">
          <el-select v-model="versionNow.simulation_node_group.image_id"
                     @change="changeSimulationImage(versionNow.simulation_node_group.image_id)"
                     prop="simulation_image_id"
                     class="full-extent-select">
            <el-option v-for="item in simulationImageOptions" :value="item.id" :label="item.name" :key="item.id">
            </el-option>
          </el-select>
<!--          <el-cascader v-model="versionNow.simulation_node_group.image_id" :options="imageOptions" :show-all-levels="false"-->
<!--                       class="full-extent-select"></el-cascader>-->
        </el-form-item>
        
      </el-form>
    </DialogBox>

    <DialogBox title="仿真信息" :visible="showParamDialog" :confirm="commitParam" :close="cancelParam">
      <el-form class="form myself-form" ref="paramForm" :model="versionNow" label-width="120px"
               :rules="paramSubmitRules">
        <el-form-item label="超参" prop="param">
          <div class="outin-box" v-for="(e, i) in parameter_list" :key="e.id">
            <div class="port-lis">
              <span class="outin-input-name-title">显示名</span>
              <el-input type="text" v-model="e.name" class="port-el-input"/>
              <span class="outin-input-name-title">参数名</span>
              <el-input type="text" v-model="e.key" class="port-el-input"/>
              <span class="outin-input-name-title">参数值</span>
              <el-input type="text" v-model="e.value" class="port-el-input"/>
            </div>
            <span class="outin-handle">
              <a href="javascript:;" @click="addParam(i)" v-if="i == parameter_list.length - 1">增加</a>
              <span v-else class="slot-btn"></span>
              <a href="javascript:;" @click="delParam(i)" v-if="parameter_list.length > 1">删除</a>
            </span>
          </div>
        </el-form-item>
      </el-form>
    </DialogBox>
  </div>
</template>

<script>
import DialogBox from '@/components/module/dialog-box.vue';
// import plugState from '@/components/module/plug-state'
import {getAllImageGroups, getAllImages, getImageDetail} from '@/api/image'
import {getAllScenarios} from '@/api/scenario'
import {mainImageRule, mainProductRule, slaveImageRule} from '@/utils/rule'
import {getAllProducts} from '@/api/product'
import {putGameTaskVersion, getGameTaskVersionDetail, putGameTask} from '@/api/gameTask'

export default {
  data() {
    return {
      status: null,
      mainNode: {},
      parameter_list: [],
      slaveNodeList: [],
      productOptions: [],
      scenarioOptions: [],
      simulationImageOptions: [],
      showSimulationDialog: false,
      showParamDialog: false,
      showEnvDialog: false,
      imageOptions: [],
      paramSubmitRules: {},
      simulationSubmitRules: {},
      submitEnvRules: {
        mainNodeImageId: [
          {required: true, validator: mainImageRule.bind(this, this), trigger: 'change'}
        ],
        mainProduct: [
          {required: true, validator: mainProductRule.bind(this, this), trigger: 'change'}
        ],
        tagImageId: [
          {required: true, validator: slaveImageRule.bind(this, this), trigger: 'change'}
        ],

      },
      versionNow: null,
      // detailData: {},
      // version: {},
      thisRouter: [],
      showTaskDialog: false,
      taskForm: {},
      taskSubmitRules: {
        name: [
          {required: true, message: "该项为必填项"},
          {required: true, min: 1, max: 40, message: "长度在1到40个字符"},
        ],
        desc: [
          {required: true, message: "该项为必填项"},
          {required: true, min: 1, max: 200, message: "长度在1到200个字符"},
        ],
      },
    };
  },

  props: ['detailData', 'version'],
  watch: {
    detailData(val) {

      this.detailDataNow = JSON.parse(JSON.stringify(val))
      this.setAddForm()
    },
    version(val) {
      console.log("version update", val)
      this.status = val.status;
      this.versionNow = JSON.parse(JSON.stringify(val))
      this.$forceUpdate()
    }
  },
  components: {
    // plugState,
    DialogBox,
  },
  created() {
    this.detailDataNow = JSON.parse(JSON.stringify(this.detailData))
    this.status = this.version.status;
    let masterNodeList = this.version.node_group_list.filter(node => node.type == 1);
    this.mainNode = masterNodeList[0]
    if (this.mainNode == undefined) {
      this.mainNode = {}
    }
    console.log("mainNode", this.mainNode)
    this.slaveNodeList = this.version.node_group_list.filter(node => node.type != 1);

    this.getAllImageGroups()
    this.getSimulationImage()
    this.changeSimulationImage(this.version.simulation_node_group.image_id)
    this.getAddForm(this.version)
    this.getProductList()
    this.versionNow = JSON.parse(JSON.stringify(this.version))
    this.versionNow = this.version
  },
  destroyed() {

  },
  methods: {
    updateTask() {
      this.taskForm = this.detailDataNow
      this.showTaskDialog = true
    },
    commitTask() {
      this.$refs.taskForm.validate(async (valid) => {
        if (valid) {
          await putGameTask(this.taskForm)
          this.$emit("getDetail")
          this.showTaskDialog = false
        }
      })
    },
    cancelTask() {
      this.showTaskDialog = false
    },
    async setAddForm() {
      console.log('this.simulation', this.simulation)
      console.log("addMainNode", this.mainNode)
      this.versionNow.node_group_list = []
      this.mainNode.type = 1
      this.mainNode.image_id = this.mainNode.image_group[2]
      this.versionNow.node_group_list.push(this.mainNode)
      for (let i = 0; i < this.slaveNodeList.length; i++) {
        this.slaveNodeList[i].type = 2
        this.slaveNodeList[i].image_id = this.slaveNodeList[i].image_group[2]
        this.versionNow.node_group_list.push(this.slaveNodeList[i])
      }
      this.versionNow.parameter_list = []
      for (let i = 0; i < this.parameter_list.length; i++) {
        if (this.parameter_list[i].name != null && this.parameter_list[i].name.length > 0) {
          if (this.parameter_list[i].name == null || this.parameter_list[i].value == null) {
            alert('参数不能为空')
          } else {
            this.versionNow.parameter_list.push(this.parameter_list[i])
          }
        }
      }
      console.log("parameter_list1", this.versionNow.parameter_list)
      console.log("parameter_list2", this.parameter_list)
    },
    async getAddForm(data) {
      this.versionNow = data
      this.port_list = []
      this.slaveNodeList = []
      for (let node of data.node_group_list) {
        if (node.type == 1) {
          this.mainNode = node
          let res = await getImageDetail({id: this.mainNode.image_id})
          let mainImage = res.data
          this.mainNode.image_group = [mainImage.visibility.toString(), mainImage.engine.toString(), mainImage.id]
        } else {
          let res = await getImageDetail({id: node.image_id})
          let slaveImage = res.data
          let slaveNode = node
          slaveNode.image_group = [slaveImage.visibility.toString(), slaveImage.engine.toString(), slaveImage.id]
          this.slaveNodeList.push(slaveNode)
        }
      }
      this.parameter_list = []
      if (data.parameter_list) {
        this.parameter_list = data.parameter_list
      }
      if (this.parameter_list.length == 0) {
        this.parameter_list.push({})
      }
    },
    updateEnv() {
      this.showEnvDialog = true
    },
    commitEnv() {
      this.setAddForm()
      this.$refs.envForm.validate(async (valid) => {
        if (valid) {
          let res = await putGameTaskVersion(this.versionNow);
          if (res && res.data) {
            this.showEnvDialog = false
            this.freshData()
          }
        }
      })
    },
    cancelEnv() {
      this.showEnvDialog = false
    },
    updateParam() {
      this.showParamDialog = true
    },
    commitParam() {
      this.setAddForm()
      this.$refs.paramForm.validate(async (valid) => {
        if (valid) {
          let res = await putGameTaskVersion(this.versionNow);
          if (res && res.data) {
            this.showParamDialog = false
            this.freshData()
          }
        }
      })
    },
    cancelParam() {
      this.showParamDialog = false
    },

    addSlaveNode() {
      let data = {type: 1, pod_num: 1}
      this.slaveNodeList.push(data)
    },
    delSlaveNode(i) {
      this.slaveNodeList.splice(i, 1)
    },
    async getAllImageGroups() {
      let res = await getAllImageGroups()
      this.imageOptions = res.data
    },
    updateSimulationEnv() {
      this.showSimulationDialog = true
    },
    async commitSimulation() {
      this.setAddForm()
      let res = await putGameTaskVersion(this.versionNow);
      if (res && res.data) {
        this.showSimulationDialog = false
        this.freshData()
      }
    },
    cancelSimulation() {
      this.showSimulationDialog = false
    },
    async getProductList() {
      let res = await getAllProducts()
      this.productOptions = res.data
    },
    async getSimulationImage() {
      let ret = await getAllImages({visibility: '1', type: 3})
      this.simulationImageOptions = ret.data
    },
    async changeSimulationImage(simulation_id) {
      console.log("changeSimulationImage")
      let ret = await getAllScenarios({imageId: simulation_id})
      console.log('ret', ret.data)
      this.scenarioOptions = ret.data

    },
    changeScenario() {
      this.$forceUpdate()
    },
    async freshData() {
      console.log("detailData")
      let res = await getGameTaskVersionDetail({id: this.versionNow.id});
      if (res && res.data) {
        this.versionNow = res.data
        this.$emit('update:version', res.data) //通过$emit触发父组件
      }
    },
    editState(state) {
      console.log(state)
    },
    addParam() {
      this.parameter_list.push({})
    },
    delParam(i) {
      this.parameter_list.splice(i, 1)
    },

  }
}
</script>
<style lang="less" scoped>
@import "~@/assets/css/code.less";
</style>
